﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;

namespace Cid.Windows
{
	public class NullableDateTimeConverter : IValueConverter
	{
		#region IValueConverter Members


		public string Format { get; set; }
		public string NullText { get; set; }
		public bool AllowNull { get; set; }
        public bool ToLowercase { get; set; }

		public NullableDateTimeConverter()
		{
			this.Format = "G";
			this.NullText = "Please specifiy a date";
			this.AllowNull = true;
            this.ToLowercase = true;
		}

		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (value == null)
			{
				if(this.AllowNull)
					return this.NullText;
				return DateTime.MinValue.ToString(this.Format);
			}

			if (value.GetType().IsGenericType)
			{
				Nullable<DateTime> nullable = (Nullable<DateTime>)value;
				if (nullable.HasValue)
					return (ToLowercase ? nullable.Value.ToString(this.Format).ToLower() : nullable.Value.ToString(this.Format));

				if (this.AllowNull)
					return this.NullText;

				return (ToLowercase ? DateTime.MinValue.ToString(this.Format).ToLower() : DateTime.MinValue.ToString(this.Format));
			}
			if ((this.AllowNull && ((DateTime)value) == DateTime.MinValue))
				return this.NullText;

            return (ToLowercase ? ((DateTime)value).ToString(this.Format).ToLower() :  ((DateTime)value).ToString(this.Format));
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			if (value != null)
			{
				DateTime date;
				if (DateTime.TryParse(value.ToString(), out date))
					return date;
			}

			if (this.AllowNull)
				return null;

			return DateTime.MinValue;
		}

		#endregion
	}	
}
